package com.dm.library.widgets;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.dm.library.R;
import com.dm.library.utils.DateUtil;
import com.dm.library.widgets.wheelview.OnWheelChangedListener;
import com.dm.library.widgets.wheelview.WheelView;
import com.dm.library.widgets.wheelview.adapters.AbstractWheelTextAdapter1;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class DatePopwindow extends Dialog implements View.OnClickListener {
    private WheelView mWheelYear;//年
    private WheelView mWheelMonth;//月
    private WheelView mWheelDay;//日
    private TextView btnSure, btnCancel;

    private ArrayList<String> yearList;//包含的年份列表
    private ArrayList<String> monthList;//包含的月份列表
    private ArrayList<String> dayList;//包含的天数列表

    private DateTextAdapter yearAdapter, monthAdapter, dayAdapter;
    private final int VisibleItems = 3;
    private Context context;

    private int maxsize = 14;
    private int minsize = 12;

    private int chooseYear, chooseMonth, chooseDay;//选择的年月日

    private DatePopwindow.OnDateListener dateListener;

    public DatePopwindow(final Context context) {
        super(context, R.style.customDialog);
        this.context = context;
        View view = View.inflate(context, R.layout.edit_date_pop_layout, null);

        mWheelYear = (WheelView) view.findViewById(R.id.wv_date_year);
        mWheelMonth = (WheelView) view.findViewById(R.id.wv_date_month);
        mWheelDay = (WheelView) view.findViewById(R.id.wv_date_day);

        btnSure = (TextView) view.findViewById(R.id.btn_myinfo_sure);
        btnCancel = (TextView) view.findViewById(R.id.btn_myinfo_cancel);


        //设置SelectPicPopupWindow的View
        this.setContentView(view);
        //设置SelectPicPopupWindow弹出窗体的宽
        //  this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        //    this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        //    this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
//		this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
 //       ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        //     this.setBackgroundDrawable(dw);

        //lyChangeAddressChild.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        initData();

        yearAdapter = new DateTextAdapter(context, yearList, 1, maxsize, minsize);
        mWheelYear.setVisibleItems(VisibleItems);//设置当前年份  滚轮0位置表示第一年
        mWheelYear.setViewAdapter(yearAdapter);
        mWheelYear.setCurrentItem(0);


        monthAdapter = new DateTextAdapter(context, monthList, 1, maxsize, minsize);
        mWheelMonth.setVisibleItems(VisibleItems);//设置当天月份
        mWheelMonth.setViewAdapter(monthAdapter);
        mWheelMonth.setCurrentItem(0);
//
        dayAdapter = new DateTextAdapter(context, dayList, 1, maxsize, minsize);
        mWheelDay.setVisibleItems(VisibleItems);
        mWheelDay.setViewAdapter(dayAdapter);
        mWheelDay.setCurrentItem(0);//设置当前显示的天数
        mWheelYear.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                String currentText = yearAdapter.getItemText(wheel.getCurrentItem()).toString();
                try {
                    chooseYear = Integer.parseInt(currentText);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }
        });

//        wvProvince.addScrollingListener(new OnWheelScrollListener() {
//
//            @Override
//            public void onScrollingStarted(WheelView wheel) {
//                // TODO Auto-generated method stub
//
//            }
//
//            @Override
//            public void onScrollingFinished(WheelView wheel) {
//                // TODO Auto-generated method stub
//                String currentText = (String) provinceAdapter.getItemText(wheel.getCurrentItem());
//                setTextviewSize(currentText, provinceAdapter);
//            }
//        });
//
        mWheelMonth.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) monthAdapter.getItemText(wheel.getCurrentItem());
                try {
                    chooseMonth = Integer.parseInt(currentText);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                // setTextviewSize(currentText, cityAdapter);

                int currentday = initDays(chooseYear, chooseMonth);//获取当月的天数
//                String[] areas = mAreaDatasMap.get(currentText);
//                initAreas(areas);
                dayAdapter = new DateTextAdapter(context, dayList, 0, maxsize, minsize);
                mWheelDay.setViewAdapter(dayAdapter);

                if (chooseDay > currentday) {
                    //联动设置滚轮位置
                    mWheelDay.setCurrentItem(getDayItem(currentday));
                }
//                wvArea.setCurrentItem(0);
//                setTextviewSize("0", areaAdapter);


            }
        });

        mWheelDay.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) dayAdapter.getItemText(wheel.getCurrentItem());
                try {
                    chooseDay = Integer.parseInt(currentText);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }


            }
        });

//        mWheelDay.addScrollingListener(new OnWheelScrollListener() {
//
//            @Override
//            public void onScrollingStarted(WheelView wheel) {
//                // TODO Auto-generated method stub
//
//            }
//
//            @Override
//            public void onScrollingFinished(WheelView wheel) {
//                // TODO Auto-generated method stub
//                String currentText = (String) areaAdapter.getItemText(wheel.getCurrentItem());
//                setTextviewSize(currentText, areaAdapter);
//            }
//        });


    }

    /**
     * 返回年的索引
     *
     * @param year 年份
     * @return
     */
    public int getYearItem(int year) {
        int size = yearList.size();
        int provinceIndex = 0;
        for (int i = 0; i < size; i++) {
            if (String.valueOf(year).equals(yearList.get(i))) {
                return provinceIndex;
            } else {
                provinceIndex++;
            }
        }
        return provinceIndex;
    }

    /**
     * 返回月的索引
     *
     * @param month 月份
     * @return
     */
    public int getMonthItem(int month) {
        int size = monthList.size();
        int provinceIndex = 0;
        for (int i = 0; i < size; i++) {
            if (String.valueOf(month).equals(monthList.get(i))) {
                return provinceIndex;
            } else {
                provinceIndex++;
            }
        }
        return provinceIndex;
    }

    /**
     * 返回日的索引
     *
     * @param day 天
     * @return
     */
    public int getDayItem(int day) {
        int size = dayList.size();
        int provinceIndex = 0;
        for (int i = 0; i < size; i++) {
            if (String.valueOf(day).equals(dayList.get(i))) {
                return provinceIndex;
            } else {
                provinceIndex++;
            }
        }
        return provinceIndex;
    }

    /**
     * 初始化数据
     */
    private void initData() {
// 格式化当前时间，并转换为年月日整型数据

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String[] split = sdf.format(new Date()).split("-");
        int currentYear = Integer.parseInt(split[0]);
        int currentMonth = Integer.parseInt(split[1]);
        int currentDay = Integer.parseInt(split[2]);


        yearList = new ArrayList<>();
        initYear(currentYear);
        monthList = new ArrayList<>();
        initMonth();
        dayList = new ArrayList<>();
        //获取当月天数
        initDays(currentYear, currentMonth);
        // 设置默认年月日为当前日期
        chooseYear = currentYear;
        chooseMonth = currentMonth;
        chooseDay = currentDay;
    }

    /**
     * 初始化月列表
     */
    private void initMonth() {
        monthList.clear();
        for (int i = 1; i <= 12; i++) {
            monthList.add(String.valueOf(i));
        }
    }

    /**
     * 初始化天列表
     *
     * @return 返回公历当年当月的天数
     */
    private int initDays(int currentYear, int currentMonth) {
        dayList.clear();
        int sumDays = DateUtil.getSumOfDayInMonthForGregorianByMonth(currentYear, currentMonth);
        for (int i = 1; i <= sumDays; i++) {
            dayList.add(String.valueOf(i));
        }
        return sumDays;
    }

    /**
     * 初始化年列表
     *
     * @param currentYear
     */
    private void initYear(int currentYear) {
        yearList.clear();
        for (int i = currentYear - 10; i <= currentYear; i++) {
            yearList.add(String.valueOf(i));
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_myinfo_cancel) {
            dismiss();

        } else if (id == R.id.btn_myinfo_sure) {
            if (dateListener != null) {
                dateListener.onClick(chooseYear, chooseMonth, chooseDay);
            }
            dismiss();

        }
    }

    /**
     * 设置日期监听器
     *
     * @param dateListener
     */
    public void setonDateListener(OnDateListener dateListener) {
        this.dateListener = dateListener;
    }

    private class DateTextAdapter extends AbstractWheelTextAdapter1 {
        ArrayList<String> list;

        protected DateTextAdapter(Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.layout.item_text, NO_RESOURCE, currentItem, maxsize, minsize);
            this.list = list;
            setItemTextResource(R.id.tempValue);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }

    }

    /**
     * 回调接口
     *
     * @author Administrator
     */
    public interface OnDateListener {
        void onClick(int year, int month, int day);
    }
    public void show(Activity activity) {
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        if (null != getWindow()) {
            getWindow().setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
            getWindow().setWindowAnimations(R.style.animBottom);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.width = display.getWidth(); //设置宽度
            getWindow().setAttributes(lp);
        }
        this.show();
    }
}